<style scoped lang="scss">
    #container {
        border: 1px solid #ddd;
    }
    
    .dnd-wrap {
        
        min-width: 120px;
        border-top: 1px solid #ddd;
        border-left: 1px solid #ddd;
        
        .node-box {
            display: flex;
            border-right: 1px solid #ddd;
            justify-content: center;
            border-bottom: 1px solid #ddd;
            align-items: center;
            min-height: 50px;
            cursor: move;
            width: 100%;
            
            .title {
                font-size: 12px;
            }
        }
        
        
    }
    
    #leftMenu {
        position: absolute;
        
        ul {
            list-style: none;
            border: 1px solid #ddd;
            margin-left: 0px;
            padding-left: 0px;;
            
            li {
                width: 120px;;
                line-height: 30px;
                cursor: pointer;
                padding-left: 5px;
                background: #fff;
                
                &:hover {
                    background: #ddd;
                }
            }
        }
        
    }
</style>
<template>
    <div style="display:flex;">
        <div class="dnd-wrap">
            <div data-type="start-event" class="node-box" @mousedown="startDrag">
                <span class="title">开始</span>
            </div>
            <div data-type="activity" class="node-box" @mousedown="startDrag">
                <span class="title">任务</span>
            </div>
            <div data-type="gateway" class="node-box" @mousedown="startDrag">
                <span class="title">网关</span>
            </div>
            <div data-type="end-event" class="node-box" @mousedown="startDrag">
                <span class="title">结束</span>
            </div>
        
        </div>
        
        <div style="flex:1;">
            <div style="padding: 10px;border:1px solid #ddd;border-left: none;">
                <!--                <el-button @click="triggerImportJson">导入json</el-button>-->
                <!--                <el-button @click="triggerJSON">导出json</el-button>-->
                <!--                <el-button @click="triggerSave">暂时缓存</el-button>-->
                <!--                <el-button @click="triggerRemote">加载数据</el-button>-->
                <el-button @click="triggerSavetoback">保存</el-button>
                <el-button @click="triggerGoBack">返回</el-button>
            </div>
            <div style="display: flex;width: 100%">
                <div style="flex:1;">
                    <div id="container"></div>
                </div>
                <div class="rightPanel">
                    <actvitiForm ref="nodeForm" v-if="isActiveType(currentItem)"></actvitiForm>
                    <edgeForm ref="nodeForm" v-if="currentItem&&currentItem.shape=='bpmn-edge'"></edgeForm>
                </div>
            </div>
        
        </div>
        
        
        <!--右键-->
        <div id="leftMenu" hidden>
            <ul>
                <li @click.stop.prevent="e=>removeNode()">删除</li>
                <!--                <li @click.stop.prevent="e=>triggerEdit()">编辑</li>-->
            </ul>
        </div>
    </div>
</template>
<script>
  import { init } from '@/initx6.js';
  import { createRect } from '@/rect.js';
  import { createCircle } from '@/circle.js';
  import { copyToClipboard } from '@/utils/cutparse.js';
  import { alertSuccess, safeParseJson, alertFail } from '@base/utils';
  import MyDialogPlus from '@codegenarate/mydialogplus';
  import axios from 'axios';
  
  import * as bpnmApi from '@/apis/bpnm.api.js';
  
  import { GridLayout, ForceLayout, DagreLayout, CircularLayout } from '@antv/layout';
  import { lodashUtils } from '@base/utils'; // umd模式下， const { GridLayout } = window.layout
  import lodash from 'lodash';
  import { createUuid } from '@/utils/index.js';
  import { deepClone, getUrlParam } from '../../../utils';
  import { findOne } from '../../../utils/lodash';
  import { isActiveType } from './bizUtils';
  
  export default {
    data() {
      return {
        isActiveType,
        graph: null,
        dnd: null,
        currentItem: undefined,
        bpmId: '',
      };
    },
    components: {
      actvitiForm: () => import('@/forms/actvitiForm.vue'),
      edgeForm: () => import('@/forms/edgeForm.vue'),
    },
    mounted() {
    
    },
    
    methods: {
      /**
       * @params .options .bnpmId
       * @desc
       * @return
       */
      async initByDialog(options) {
        var self = this;
        this.bpmId = options && options.bpmId;
        var { graph, dnd } = init('container', {
          click: self.clickEvent,
          bpmId: options && options.bpmId,
        });
        this.dnd = dnd;
        this.graph = graph;
        
        
        var result = (await this.getJsonbybnpmId(this.bpmId));
        var json = result && result.data;
        //默认 填充一些默认的width height
        var nodes = json && json.pipelineList || [];
        for (let i = 0; i < nodes.length; i++) {
          var nodeName = nodes[i].nodeName;
          var  confluenceType = nodes[i].confluenceType;
          nodes[i].id = `${nodes[i].id || 0}`;
          nodes[i].data = deepClone(nodes[i]);
  
          nodes[i].ordering = 1;
          
          if (confluenceType ==15/* '开始'*/) {
            nodes[i].shape = 'start-event';
            nodes[i].label = nodeName;
            nodes[i].width = 50;
            nodes[i].height = 50;
  
  
            
            
          } else if (confluenceType == 20 /*'结束'*/) {
            nodes[i].shape = 'end-event';
            nodes[i].label = nodeName;
            nodes[i].width = 50;
            nodes[i].height = 50;
          } else {
            nodes[i].shape = 'activity';
            nodes[i].label = nodeName;
            nodes[i].width = 100;
            nodes[i].height = 50;
          }
          
          
        }
        
        var edges1 = json && json.lineList || [];
        var newEdages = [];
        for (let i = 0; i < edges1.length; i++) {
        
          var exitSourceNode = findOne(nodes, item => item.id == edges1[i].sourceNodeId);
          var exitTargetNode = findOne(nodes, item => item.id == edges1[i].targetNodeId);
          if (!(exitSourceNode && exitTargetNode)) {
            continue;
          }
          newEdages.push({
            shape: 'bpmn-edge',
            data: edges1[i],
            id: edges1[i].id,
            source: {
              cell: `${edges1[i].sourceNodeId}`,
              port: 'port3',
            },
            target: {
              cell: `${edges1[i].targetNodeId}`,
              connectionPoint: 'boundary', // 没有参数时可以简化写法
            },
          });
        }
        
        
        
        
        var temjson = {
          nodes: nodes,
          edges: newEdages,
        };

        var layout = new DagreLayout({
          type: 'dagre',
          rankdir: 'T', // 可选，默认为图的中心
        });
        console.log('temjson', JSON.stringify(temjson));
        const newmodel = layout.layout(temjson);
        //debugger
        this.graph.fromJSON(newmodel);
        
        
        //控制 line 有表达式的特色标记
        this.setConditionLineRect(newEdages);
        
        
      },
      //控制 line 有表达式的特色标记
      setConditionLineRect(lines) {
        for (let i = 0; i < lines.length; i++) {
          var cell = this.graph.getCellById(lines[i].id);
          if (lines[i] && lines[i].data && lines[i].data.hasCondition==5 /*有表达式*/) {
            cell.setAttrByPath('signRect/opacity', 1);
          }
        }
      },
      async getJsonbybnpmId(id) {
        if (!id) return undefined;
        var json = await bpnmApi.getJsonbyBnpmId({ bpmId: id });
        return json;
      },
      clickEvent(node) {
        this.currentItem = node;
        if (node.shape == 'activity'||node.shape == 'start-event'||node.shape == 'end-event') {
          setTimeout(() => {
            this.$refs['nodeForm'].initByDialog({
              node: node,
              data: node && node.data,
              bpmId: getUrlParam('bpmId'),
            });
          }, 100);
        } else if (node.shape == 'bpmn-edge') {
          setTimeout(() => {
            this.$refs['nodeForm'].initByDialog({
              node: node,
              data: node && node.data,
              lineId: node && node.data && node.data.id,
              bpmId: getUrlParam('bpmId'),
            });
          }, 100);
        }
        
      },
      
      async startDrag(e) {
        let data = undefined;
        var node = undefined;
        var type = e.currentTarget.dataset.type;
        //var id = createUuid();
        if (type === 'activity') {
          node = this.graph.createNode({
            shape: type,
          });
        } else if (type === 'start-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '开始',
              },
            },
          });
        } else if (type === 'end-event') {
          node = this.graph.createNode({
            shape: type,
            attrs: {
              label: {
                text: '结束',
              },
            },
          });
        } else if (type === 'gateway') {
          node = this.graph.createNode({
            shape: type,
          });
        }
        
        console.log('node', node, e);
        this.dnd.start(node, e);
      },
      removeNode() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        var cell = this.graph.getCellById(nodeId);
        if (cell && cell.id) {
          this.graph.removeNode(cell.id);
          document.documentElement.querySelector('#leftMenu').style.display = 'none';
          
          //axois  删除节点
          if (cell.shape == 'activity' ||
            cell.shape == 'end-event' ||
            cell.shape == 'start-event') {
            bpnmApi.delNode(cell.id)
          } else if (cell.shape == 'bpmn-edge') {
            bpnmApi.delLine(cell.id)
          }
          
        }
      },
      async triggerEdit() {
        var nodeId = sessionStorage.getItem('contextmenu_current_node_id');
        if (nodeId) {
          var cellItem = this.graph.getCellById(nodeId);
          var result = await MyDialogPlus({
            title: '导入json',
            components: {
              modify: () => import('@/dialog/importin.vue'),
            },
          });
        }
        
      },
      /**
       * @description: 暂时缓存
       * @params
       * @return
       */
      triggerSave() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
        sessionStorage.setItem('save_json_graph', JSON.stringify(json));
      },
      triggerGoBack() {
        location.href = '/src/views/bnpmList/index.html';
      },
      
      /**
       * @description:
       * @params
       * @return
       */
      async triggerSavetoback() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('submit json===>', json);
        copyToClipboard(JSON.stringify(json));
        //alertSuccess('已复制到粘贴板上');
        sessionStorage.setItem('save_json_graph', JSON.stringify(json));
        
        
        var nodes = [];
        var mesBpmLines = [];
        for (let i = 0; i < json.cells.length; i++) {
          var cell = json.cells[i];
          if (cell.shape === 'activity') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'end-event') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'start-event') {
            cell.thirdPartId = cell.id;
            nodes.push(cell.data);
          } else if (cell.shape === 'bpmn-edge') {
            
            var sourceNode = this.graph.getCellById(cell.source.cell);
            var targetNode = this.graph.getCellById(cell.target.cell);
            if (sourceNode && targetNode && sourceNode.data.id && targetNode.data.id) {
              mesBpmLines.push({
                sourceNodeId: sourceNode && sourceNode && sourceNode.data.id,
                targetNodeId: targetNode && targetNode && targetNode.data.id,
              });
            }
            
            
          }
        }
        
        const result = await axios.post('/api1/mesBpmPipeline/saveComprehensive', {
          bpmId: this.bpmId,
          nodes,
          mesBpmLines,
        });
        if (result && result.success) {
          alertSuccess('保存成功');
        }
      },
      
      
      /**
       * @description:  加载数据
       * @params
       * @return
       */
      async triggerRemote() {
        const resultEntity = await axios.post('/api1/mesBpmPipeline/listComprehensive', {
          bpmId: 2,
        }).then(res => res.data);
        
        var data = resultEntity.data;
        var nodes = data.nodes || [];
        var edges = data.mesBpmLines || [];
        
        var newNodes = [];
        var newEdages = [];
        
        
        for (let i = 0; i < nodes.length; i++) {
          var one = nodes[i];
          var oneNode = undefined;
          if (one.nodeName == '开始') {
            oneNode = ({
              shape: 'start-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else if (one.nodeName == '结束') {
            oneNode = ({
              shape: 'end-event',
              id: `${one.id}`,
              data: one,
              width: 50,
              height: 50,
              attrs: {
                width: 50,
                height: 50,
                label: { text: one.nodeName },
              },
            });
          } else {
            oneNode = ({
              shape: 'activity',
              id: `${one.id}`,
              data: one,
              width: 100,
              height: 50,
              label: `${one.id}--${one.nodeName}`,
              attrs: {
                width: 100,
                height: 50,
              },
            });
          }
          
          newNodes.push(oneNode);
          
        }
        
        
        /*================  开始 画线 */
        for (let i = 0; i < edges.length; i++) {
          var edge = edges[i];
          newEdages.push({
            id: edge.id,
            shape: 'bpmn-edge',
            //label: '我是表达式',
            source: {
              cell: `${edge.sourceNodeId}`,
              port: 'port3',
            },
            target: {
              cell: `${edge.targetNodeId}`,
              connectionPoint: 'boundary', // 没有参数时可以简化写法
            },
          });
        }
        
        
        const model = { nodes: newNodes, edges: newEdages };
        
        
        var layout = new DagreLayout({
          type: 'dagre',
          rankdir: 'T', // 可选，默认为图的中心
        });
        const newmodel = layout.layout(model);
        this.graph.fromJSON(newmodel);
      },
      
      triggerJSON() {
        var self = this;
        var json = self.graph.model.toJSON();
        console.log('json', json);
        copyToClipboard(JSON.stringify(json));
        alertSuccess('已复制到粘贴板上');
      },
      async triggerImportJson() {
        
        var result = await MyDialogPlus({
          title: '导入json',
          components: {
            modify: () => import('@/dialog/importin.vue'),
          },
          
        });
        if ((result && result.success)) {
          var json = JSON.parse(result.data);
          this.graph.fromJSON(json);
          alertSuccess('导入成功');
          
        }
        
      },
      
    },
  };
</script>
